package com.zy.struts.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zy.struts.domain.User;
import com.zy.struts.util.HibernateSessionFactory;

public class UserDAOImpl implements UserDAO {

	public User login(String name, String password) {
		User user = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			user = null;
			Query query = session
					.createQuery("from User where name=:name and password=:password");
			query.setString("name", name);
			query.setString("password", password);

			user = (User) query.uniqueResult();
			if (null != user) {
				user.setFlag(true);
				session.update(user);
				tx.commit();
				System.out.println("user flag:" + user.isFlag());
			}
		} finally {
			if (null != session)
				session.close();
		}

		return user;
	}

	public void loginSet() {

	}

	public List<User> getOnlineUsers() {
		List<User> list = new ArrayList<User>();
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			Query query = session.createQuery("from User where flag=:flag");
			query.setBoolean("flag", true);
			list = query.list();

		} finally {
			if (null != session)
				session.close();
		}
		return list;
	}

	public User getUser(String id) {
		User user=null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			user=(User)session.get(User.class,id);
			tx.commit();
		} finally {
			if (null != session)
				session.close();
		}
		return user;
	}

}
